package com.creative.xcx.service.Impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import com.creative.core.page.TableDataInfo;
import com.creative.user.service.UserInfoService;
import com.creative.xcx.domain.UploadHistory;
import com.creative.xcx.domain.UserFavorite;
import com.creative.xcx.domain.vo.UploadHistoryVo;
import com.creative.xcx.domain.vo.UploadStatisticsVo;
import com.creative.xcx.domain.vo.UserFavoriteVo;
import com.creative.xcx.mapper.UploadHistoryMapper;
import com.creative.xcx.service.UploadHistoryService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import static com.creative.xcx.domain.constant.common.CACHE_FAVORITE_KEY;
import static com.creative.xcx.domain.constant.common.CACHE_UPLOAD_KEY;

/**
 * @author ling
 * @description 上传记录
 * @date 2025-03-15
 */
@Service
public class UploadHistoryServiceImpl implements UploadHistoryService {

    @Resource
    private UploadHistoryMapper uploadHistoryMapper;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Integer insert(UploadHistory uploadHistory) {
        uploadHistory.setUploadTime(DateUtil.date());
        return uploadHistoryMapper.insert(uploadHistory);
    }

    @Override
    public Integer delete(Long id) {
        if(uploadHistoryMapper.selectById(id) == null){
            return 0;
        }
        return uploadHistoryMapper.delete(id);
    }


    @Override
    public Integer deleteBatch(Long[] ids) {
        return uploadHistoryMapper.deleteBatch(ids);
    }


    @Override
    public Integer update(UploadHistory uploadHistory) {

        return uploadHistoryMapper.update(uploadHistory);
    }

    @Override
    public UploadHistory selectById(Long id) {
        return uploadHistoryMapper.selectById(id);
    }

    @Override
    public  List<UploadHistoryVo> selectUploadHistoryList(UploadHistory uploadHistory) {
        //        查看缓存是否存在
        String key = CACHE_UPLOAD_KEY + uploadHistory.getUserId();
        if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(key))) {
            // 计算分页游标
            long start = ((uploadHistory.getPageNum() - 1L) * uploadHistory.getPageSize());
            long end = start + uploadHistory.getPageSize() - 1;
            // 从Redis获取分页素材ID
            Set<String> materialIds = stringRedisTemplate.opsForZSet()
                    .reverseRange(key, start, end);
//            遍历分页素材ID
            System.out.println("查询列表：");
            for (String materialId : materialIds){
                System.out.println(materialId);
            }
            if (materialIds == null || materialIds.isEmpty()) {
                return Collections.emptyList();
            }
//            将set集合转为list
            List<String> materialIdList = materialIds.stream().toList();

            // 批量查询素材详情
            return uploadHistoryMapper.batchGetMaterials(uploadHistory.getUserId(), materialIdList);
        } else {
            //     不存在缓存，则添加缓存，可以新开一个线程，做这个操作
            insertCache(uploadHistory.getUserId());
            //获取当前用户的收藏列表
            PageHelper.startPage(uploadHistory.getPageNum(), uploadHistory.getPageSize());
            List<UploadHistoryVo> list = uploadHistoryMapper.selectUploadHistoryList(uploadHistory);
            Page<UploadHistoryVo> page = (Page<UploadHistoryVo>) list;

            return page.getResult();
        }
    }

    @Override
    public List<UploadHistory> exportBatch(Long[] ids) {
        return uploadHistoryMapper.exportBatch(ids);
    }

    @Override
    public List<UploadStatisticsVo> calculateUploadMaterial() {
        return uploadHistoryMapper.calculateUploadMaterial();
    }

    @Override
    public Long calculateUploadNum() {
        return uploadHistoryMapper.calculateUploadNum();
    }

    // 数据库加载缓存(全部添加)
    private void insertCache(String userId) {
        List<UploadHistory> dbData = uploadHistoryMapper.selectByUserId(userId);
        if (!dbData.isEmpty()) {
//           遍历数据，将数据添加到Redis中
            for (UploadHistory uploadHistory : dbData) {
                stringRedisTemplate.opsForZSet().add(CACHE_UPLOAD_KEY + userId, uploadHistory.getMaterialId(), uploadHistory.getUploadTime().getTime());
            }
        }
    }
}
